import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Select } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { getAssetList, createAsset, updateAsset, deleteAsset, getDepartmentList } from '../../services/api';

const AssetList = () => {
  const [assets, setAssets] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingAsset, setEditingAsset] = useState(null);
  const user = JSON.parse(sessionStorage.getItem('user') || '{}');

  const fetchAssets = async () => {
    setLoading(true);
    try {
      const response = await getAssetList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setAssets(response.data);
      } else {
        setAssets([]);
        message.error(response.message || '获取资产列表失败');
      }
    } catch (error) {
      console.error('获取资产列表失败:', error);
      message.error('获取资产列表失败');
      setAssets([]);
    }
    setLoading(false);
  };

  const fetchDepartments = async () => {
    try {
      const response = await getDepartmentList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setDepartments(response.data);
      } else {
        setDepartments([]);
        message.error(response.message || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
      setDepartments([]);
    }
  };

  useEffect(() => {
    fetchAssets();
    fetchDepartments();
  }, []);

  const handleAdd = () => {
    setEditingAsset(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingAsset(record);
    form.setFieldsValue({
      assetId: record.assetId,
      assetName: record.assetName,
      depId: record.depId,
      totalNum: record.totalNum
    });
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await deleteAsset(id);
      message.success('删除成功');
      fetchAssets();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingAsset) {
        await updateAsset(editingAsset.assetId, values);
        message.success('更新成功');
      } else {
        await createAsset(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchAssets();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const columns = [
    {
      title: '资产ID',
      dataIndex: 'assetId',
      key: 'assetId',
    },
    {
      title: '资产名称',
      dataIndex: 'assetName',
      key: 'assetName',
    },
    {
      title: '状态',
      dataIndex: 'assetStatus',
      key: 'assetStatus',
    },
    {
      title: '所属部门',
      dataIndex: 'depId',
      key: 'depId',
      render: (depId) => departments.find(d => d.depId === depId)?.depName || depId,
    },
    {
      title: '当前数量',
      dataIndex: 'assetNum',
      key: 'assetNum',
    },
    {
      title: '总数量',
      dataIndex: 'totalNum',
      key: 'totalNum',
    },
    user?.admin === 'yes' && {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.assetId)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ].filter(Boolean);

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '16px'
      }}>
        <h2>资产管理</h2>
        {user?.admin === 'yes' && (
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加资产
          </Button>
        )}
      </div>
      
      <Table
        columns={columns}
        dataSource={assets}
        loading={loading}
        rowKey="assetId"
      />

      <Modal
        title={editingAsset ? '编辑资产' : '添加资产'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="assetId"
            label="资产ID"
            rules={[{ required: true, message: '请输入资产ID' }]}
          >
            <Input disabled={!!editingAsset} />
          </Form.Item>
          <Form.Item
            name="assetName"
            label="资产名称"
            rules={[{ required: true, message: '请输入资产名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="depId"
            label="所属部门"
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <Select>
              {departments.map(dept => (
                <Select.Option key={dept.depId} value={dept.depId}>
                  {dept.depName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="totalNum"
            label="总数量"
            rules={[{ required: true, message: '请输入总数量' }]}
          >
            <Input type="number" min={0} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AssetList; 